package org.paul.tourism

import android.app.Application
import android.content.IntentFilter
import android.net.ConnectivityManager

/**
 *
 *
 *  created by paul at 2019-03-26
 *
 */

class Tourism : Application(), Logger {

    companion object {
        private var instance: Tourism? = null
        fun instance() = instance!!
    }

    override fun onCreate() {
        super.onCreate()
        instance=this
        registerNetworkChangeListener()
    }

    private fun registerNetworkChangeListener() {
        d("register the network change listener broadcaster receiver in application.")
        //注册网路状态监听.//因为android sdk 24 后不支持静态注册网络状态改变广播.
        val receiver = ActiveReceiver()
        val filter = IntentFilter()
        @Suppress("DEPRECATION")
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        //因为是在 application 注册的 ，且该广播为全局广播，故没有注销.
        registerReceiver(receiver, filter)
    }

    fun <T : NetChangeAudience> subscribeNetChange(t: T) {
        audiences.add(t)
    }

    fun <T : NetChangeAudience> unSubscribeNetChange(t: T) {
        audiences.remove(t)
    }

    fun broadcast(connected: Boolean) {
        audiences.forEach {
            if (connected) {
                it.onLine()
            } else {
                it.offLine()
            }
        }
    }

    private val audiences = ArrayList<NetChangeAudience>()

}
